//
//  15.反转链表.swift
//  数据结构与算法
//
//  Created by ZERO on 2021/5/18.
//

import Foundation
/*
 题目：输入一个链表，反转链表后，输出新链表的表头。
 思路：这个很简单，我们使⽤三个指针，分别指向当前遍历到的结点、它的前⼀个结点以及后⼀个结点。 在遍历的时候，做当前结点的尾结点和前⼀个结点的替换。
 */
func offer_15() {
    let node1 = Solution.LinkNode(val: 1)
    let node2 = Solution.LinkNode(val: 2)
    let node3 = Solution.LinkNode(val: 3)
    let node4 = Solution.LinkNode(val: 4)
    let node5 = Solution.LinkNode(val: 5)
    node1.next = node2
    node2.next = node3
    node3.next = node4
    node4.next = node5
    print(Solution().reverseList(node1)?.val ?? "无结点")
}

fileprivate class Solution {
    class LinkNode {
        var val: Int
        var next: LinkNode?
        init(val: Int) {
            self.val = val
        }
    }
    
    func reverseList(_ head: LinkNode?) -> LinkNode? {
        // write code here
        var before: LinkNode? = nil
        var current = head
        var after: LinkNode? = nil
        while current != nil {
            after = current?.next
            current?.next = before
            before = current
            current = after
        }
        return before
    }
}

